package com.viu.technology.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Map;

/**
 * 发送邮件工具类
 */
@Component
public class EmailUtil {


    @Autowired
    private JavaMailSender mailSender;

    String fromEmail = "13178898959@163.com";

    /**
     * 发送纯文本邮件
     * @param toEmail
     * @param subject
     * @param text
     * @return
     */
    public boolean sendTextEmail(String toEmail,String subject,String text) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(fromEmail);
        message.setTo(toEmail);
        message.setSubject(subject);
        message.setText(text);

        try {
            mailSender.send(message);
        } catch (MailException e) {
            return false;
        }
        return true;
    }


    /**
     * 发送带有附件的邮件
     * @param toEmail
     * @param subject
     * @param text
     * @param files
     * @return
     */
    public boolean sendAttachmentsMail(String toEmail, String subject, String text, Map<String, File> files) {

        MimeMessage mimeMessage = mailSender.createMimeMessage();

        try {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(fromEmail);
            helper.setTo(toEmail);
            helper.setSubject(subject);
            helper.setText(text);

            for (Map.Entry<String, File> entry : files.entrySet()) {
                helper.addAttachment(entry.getKey() , entry.getValue());
            }

            mailSender.send(mimeMessage);

        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        }

        return true;

    }



    /**
     * 带有HTML的邮件
     * @param toEmail
     * @param subject
     * @param text
     * @return
     */
    public boolean sendInlineMail(String toEmail, String subject, String text) {

        MimeMessage mimeMessage = mailSender.createMimeMessage();

        try {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(fromEmail);
            helper.setTo(toEmail);
            helper.setSubject(subject);
            helper.setText(text, true);

            FileSystemResource file = new FileSystemResource(new File("weixin.jpg"));
            helper.addInline("technology-integration", file);

            mailSender.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }
}
